package com.feature.core.rabbitmq;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

public class FastJson2MessageConverter extends AbstractMessageConverter {
    private static final String DEFAULT_CHARSET = "UTF-8";
    private String charset = DEFAULT_CHARSET;
    private JSONWriter.Feature[] writerFeatures = new JSONWriter.Feature[] { JSONWriter.Feature.WriteClassName };
    private JSONReader.Feature[] readerFeatures = new JSONReader.Feature[] { JSONReader.Feature.SupportAutoType };

    @Override
    protected Message createMessage(Object object, MessageProperties messageProperties) {
        try {
            byte[] bytes = JSON.toJSONBytes(object, writerFeatures);
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            messageProperties.setContentEncoding(charset);
            if (bytes != null) {
                messageProperties.setContentLength(bytes.length);
            }
            return new Message(bytes, messageProperties);
        } catch (Exception e) {
            throw new MessageConversionException("FastJSON2 序列化失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        try {
            String content = new String(message.getBody(), charset);
            String typeId = message.getMessageProperties().getHeader("__TypeId__");
            if (typeId != null) {
                Class<?> clazz = Class.forName(typeId);
                return JSON.parseObject(content, clazz, readerFeatures);
            }
            return JSON.parseObject(content, Object.class, readerFeatures);
        } catch (Exception e) {
            throw new MessageConversionException("FastJSON2 反序列化失败: " + e.getMessage(), e);
        }
    }

    public void setWriterFeatures(JSONWriter.Feature... features) {
        this.writerFeatures = features;
    }

    public void setReaderFeatures(JSONReader.Feature... features) {
        this.readerFeatures = features;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
}